package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.DamageListDao;
import com.atguigu.jxc.dao.DamageListGoodsDao;
import com.atguigu.jxc.entity.DamageList;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.service.DamageListGoodsService;
import com.atguigu.jxc.service.GoodsService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dxt
 * @create 2025-07-16-19:07
 */
@Service
public class DamageListGoodsServiceImpl implements DamageListGoodsService {

    @Autowired
    private DamageListDao damageListDao;

    @Autowired
    private DamageListGoodsDao damageListGoodsDao;

    @Autowired
    private GoodsService goodsService;

    /**
     * 保存报损单
     * @param damageList
     * @param damageListGoodsStr
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(DamageList damageList, String damageListGoodsStr) {
        Gson gson = new Gson();
        Type listType = new TypeToken<List<DamageListGoods>>(){}.getType();
        List<DamageListGoods> damageListGoodsList = gson.fromJson(damageListGoodsStr, listType);
        damageListDao.insert(damageList);
        for (DamageListGoods damageListGoods : damageListGoodsList) {
            damageListGoodsDao.save(damageList, damageListGoods);
            goodsService.subtractStock(damageListGoods.getGoodsId(), damageListGoods.getGoodsNum());
        }
    }

    /**
     * 查询报损单
     * @param sTime 开始时间
     * @param eTime 结束时间
     * @return
     */
    @Override
    public Map<String, Object> getList(String sTime, String eTime) {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<DamageList> list = damageListDao.selectList(sTime, eTime);
        resultMap.put("rows", list);
        return resultMap;
    }

    /**
     * 查询报损单商品
     * @param damageListId 报损单Id
     * @return
     */
    @Override
    public Map<String, Object> getGoodsList(Integer damageListId) {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<DamageListGoods> damageListGoodsList = damageListGoodsDao.selectGoodsList(damageListId);
        resultMap.put("rows", damageListGoodsList);
        return resultMap;
    }
}
